package midi.midi.IO;

import midi.midi.Common.MidiUtil;
import midi.midi.MTrk.MTrk;
import midi.midi.Message.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * 把HTrk转换成byte
 */
public class MTrkIO {

    public static byte[] getByte(MTrk mTrk) {
        List<byte[]> byteList = new ArrayList<byte[]>();
        int len = 0;
        for (Message message : mTrk.getMessageList()) {
            byte[] b = MessageIO.getByte(message);
            len += b.length;
            byteList.add(b);
        }


        byte[] br = new byte[4 + 4 + len];
        //Mtrk头部
        br[0] = 'M';
        br[1] = 'T';
        br[2] = 'r';
        br[3] = 'k';
        //字节数目
        byte[] blen = midi.midi.Common.MidiUtil.intToByteArray(len);
        for (int i = 0; i <= 4 - 1; i++) {
            br[i + 4] = blen[i];
        }
        //事件
        int p = 8;
        for (byte[] b : byteList) {
            for (byte b1 : b) {
                br[p] = b1;
                p++;
            }

        }
        return br;
    }
}
